package com.xiguaji.tiktok.task.blogger.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.gugee.tiktok.common.model.dal.blogger.TBloggerRepository;
import com.gugee.tiktok.common.model.dto.SlimBloggerDto;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.EventBusTemplate;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.SneakyThrows;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;

@Component
public class MonitorBloggerMainEventListener implements IEventListener<MonitorBloggerMainEventListener.MonitorBloggerMainEvent> {

    @Autowired
    TBloggerRepository tBloggerRepository;

    @Autowired
    @Lazy
    EventBusTemplate eventBusTemplate;

    ForkJoinPool forkJoinPool= ThreadPoolUtils.forkJoinPool(50,"MonitorBloggerMain-worker");

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(MonitorBloggerMainEvent event) {
        List<SlimBloggerDto> bloggers = tBloggerRepository.getAllGroupUid();

        // bloggers.removeIf( slimBloggerDto ->  slimBloggerDto.getUid() != 5831967);

        XxlJobLogger.log("MonitorBloggerMain bloggerSize:{}",bloggers.size());


        try {
            forkJoinPool.submit(()->bloggers.parallelStream().forEach(b ->{

                var saveBloggerEvent = new UpdateBloggerMainEventListener.UpdateBloggerMainEvent(event, bloggers,true);
                eventBusTemplate.post(saveBloggerEvent);

                val monitorBloggerMainRecordEvent = new MonitorBloggerMainRecordEventListener.MonitorBloggerMainRecordEvent(event, bloggers);
                eventBusTemplate.post(monitorBloggerMainRecordEvent);
            })).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    public static class MonitorBloggerMainEvent extends Event {

        public MonitorBloggerMainEvent() {
            super("MonitorBloggerMain");
        }
        public MonitorBloggerMainEvent(int upCnt) {
            super("MonitorBloggerMain");
            this.upCnt=upCnt;
        }
        private  int  upCnt;

    }
}
